<?php

namespace app\api\controller;
use think\Controller;
use think\Db;

/**
 * swagger: 文章
 */
class Orders extends Base
{
	//订单列表
    public function lists()
    {
        $type = input("type", 0, "intval");
        $page = input("page", 1, "intval");
        $member_id = input("member_id", 0, "intval");
		$list = null;
		//当前时间
		$nowdate1 = date('Y-m-d');
		$nowtime = date('H:i:s');
		$map =  [];
		$map['a.orders_time'] = array('egt',$nowdate1);
		//$map['b.start_time'] = array('egt',$nowtime);
        switch ($type) {
                //查询全部订单
            case 0:
				$list = db("place_orders")->alias("a")
				->join("place_manager b", 'a.manager_id = b.manager_id')
				->join("place_types c", 'c.types_id = b.types_id')
				->field('a.*,b.manager_name,c.types_name')
				->where("a.member_id", $member_id)
				->where($map)
				->order("a.orders_id desc")->page($page, 8)->select();
                break;
                //退款订单
            case 1:
                $list = db("place_orders")->alias("a")
				->join("place_manager b", 'a.manager_id = b.manager_id')
				->join("place_types c", 'c.types_id = b.types_id')
				->field('a.*,b.manager_name,c.types_name')
				->where(["a.member_id" => $member_id, 'a.status' => ['in', '2,4,5']])
				->where($map)
				->order("a.orders_id desc")->page($page, 8)->select();
                break;
                //待使用订单
            case 2:
                $list = db("place_orders")->alias("a")
				->join("place_manager b", 'a.manager_id = b.manager_id')
				->join("place_types c", 'c.types_id = b.types_id')
				->field('a.*,b.manager_name,c.types_name')
				->where(["a.member_id" => $member_id, 'a.status' => '0'])
				->where($map)
				->order("a.orders_id desc")->page($page, 8)->select();
                break;
                //已完成订单
            case 3:
                $list = db("place_orders")->alias("a")
				->join("place_manager b", 'a.manager_id = b.manager_id')
				->join("place_types c", 'c.types_id = b.types_id')
				->field('a.*,b.manager_name,c.types_name')
				->where(["a.member_id" => $member_id, 'a.status' => '1'])
				->where($map)
				->order("a.orders_id desc")->page($page, 8)->select();
                break;
            default:
                $list = db("place_orders")->alias("a")
				->join("place_manager b", 'a.manager_id = b.manager_id')
				->join("place_types c", 'c.types_id = b.types_id')
				->field('a.*,b.manager_name,c.types_name')
				->where("a.member_id", $member_id)
				->where($map)
				->order("a.orders_id desc")->page($page, 8)->select();
                break;
        }
		//echo  db("place_orders")->getLastSql();
		$list = $this->array_time_change($list, 'create_time', 'Y-m-d H:i:s');
        $this->success("success", array_merge($list));
	}
	//取消预约
    public function order_refund()
    {
        $order_id = input("order_id", 0, "intval");
         $z_id = input("z_id", 0, "intval");
       // $member_id = input("member_id", 0, "intval");
        $refund_desc = input("refund_desc", ''); //退款描述

        
        db("place_orders")->where("orders_id", $order_id)->update(['status' => '2', 'update_time' => time(),'remark'=> $refund_desc ]);

        $this->success("退约成功");
	}
	//获取星期方法
    function   get_week($date){
        //强制转换日期格式
        $date_str=date('Y-m-d',strtotime($date));
   
        //封装成数组
        $arr=explode("-", $date_str);
        
        //参数赋值
        //年
        $year=$arr[0];
        
        //月，输出2位整型，不够2位右对齐
        $month=sprintf('%02d',$arr[1]);
        
        //日，输出2位整型，不够2位右对齐
        $day=sprintf('%02d',$arr[2]);
        
        //时分秒默认赋值为0；
        $hour = $minute = $second = 0;   
        
        //转换成时间戳
        $strap = mktime($hour,$minute,$second,$month,$day,$year);
        
        //获取数字型星期几
        $number_wk=date("w",$strap);
        
        //自定义星期数组
        $weekArr=array("星期日","星期一","星期二","星期三","星期四","星期五","星期六");
        
        //获取数字对应的星期
        return $weekArr[$number_wk];
    }
	//取消预约
    public function yu()
    {
       $types_id = input("type", 0, "intval");
       $member_id = input("member_id", 0, "intval");
	   $nowdate1 = date('Y-m-d');
	   $nowtime = date('H:i:s');	  
	   $pmap =  [];
	   $pmap['start_time'] = array('egt',$nowtime);

       $weeklist = array();
        for ($x=0; $x<7; $x++) {
			$week = array();
			$id = $x;
			$nowdate = date('Y-m-d',strtotime('+'.$x.' day'));
			$weekdate = date('m-d',strtotime('+'.$x.' day'));
			$weekname = $this->get_week($nowdate);
			//当天预订筛选
			// $list = db("place_manager")->alias("a")
			// ->field('a.*')
			// ->join("place_orders b", 'a.manager_id = b.manager_id')
			// ->where("a.types_id", $types_id)
			// ->where("b.orders_time", $nowdate1)
			// ->order("a.manager_no asc,a.start_time asc")->select();
			$order_manger = db("place_orders")->field("manager_id")->where("types_id", $types_id)
			->where("orders_time", $nowdate)->where("status","0")->select();
			// echo  db("place_orders")->getLastSql();
			// echo "\r\n";
			$new=array();
			foreach($order_manger as $ass){
				$new[]=$ass['manager_id'];
			}
			$map['manager_id'] = array('not in',$new);
			if($x==0)
			$list = db("place_manager")->where("types_id", $types_id)
			->where($map)
			->where($pmap)
			->order("manager_no asc,start_time asc")->select();
			else
			$list = db("place_manager")->where("types_id", $types_id)
			->where($map)
			->order("manager_no asc,start_time asc")->select();
			// echo  db("place_orders")->getLastSql();
			// echo "\r\n";
			$week = array('id'=>$id,'weekname'=>$weekname,'weekdate'=>$weekdate,'nowdate'=>$nowdate,'wlist'=>$list);
            array_push($weeklist,$week);
          } 
		
	   
	   //进行修改状态 是已预约 已过期 还是可预约

       $this->success("获取成功",['weeklist' => $weeklist]);
	}
	public function manager_yu()
	{
		$manager_id = input("manager_id", 0, "intval");
		$result = db("place_manager")->alias("a")
		->field('a.*,b.types_name')
		->join("place_types b", 'a.types_id = b.types_id')
		->where(["a.manager_id" => $manager_id, "a.status" => ['neq', '0']])->find();
		$this->success("查询成功", ['result' => $result]);
	}
	public function create()
	{
		$manager_id = $this->request->request('manager_id');
		$member_id = $this->request->request('member_id');
		$select_date = $this->request->request('select_date');
		$types_id = $this->request->request('types_id');
		$remark = $this->request->request('remark');
		$data["manager_id"] = $manager_id;
		$data["member_id"] = $member_id;
		$data["orders_time"] = $select_date;
		$data["types_id"] = $types_id;
		$data["remark"] = $remark;
		$data["create_time"] = time();
		$data["update_time"] = time();
		$id = db("place_orders")->insertGetId($data);
		$order = db("place_orders")->alias("a")
		->join("place_manager b", 'a.manager_id = b.manager_id')
		->join("place_types c", 'c.types_id = a.types_id')
		->join("member m", 'a.member_id = m.id')
		->join("third_wxapp t", 't.user_id = a.member_id ')
		->field('a.orders_time,m.mobile,b.manager_name,c.types_name,t.open_id,b.start_time,b.end_time')
		->where("a.orders_id", $id)->find();
		// echo  db("place_orders")->getLastSql();
		// 	echo "\r\n";
		//获取memeber_id 的openId 手机号码 
		$txt_name = $order['types_name'].$order['manager_name'];
		 $txt_info = $order['orders_time'].' '.$order['start_time']  ;
		//$txt_info = $order['orders_time'].'请在预约的时间到达场馆！';
		$this->sendMsg($order["open_id"],'G1Y8ii8uz7OOk_p4DA3xDFWQSURSncs4Wiiygp16Wbk',$order['mobile'],$txt_name ,$txt_info);
		$this->success("预约已申请");
	}

	public function sendMsg($touser,$template_id,$mobile,$txt_name,$txt_info)
	{
		 //获取access_token
        $accessToken = new AccessToken();
		$access_token = $accessToken ->getAccessToken();
		 //请求url
		$url = 'https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token=' . $access_token ;
		//发送内容
		$data = [] ;

		//接收者（用户）的 openid
		$data['touser'] = $touser ;
	
		//所需下发的订阅模板id
		$data['template_id'] = $template_id ;
	
		//点击模板卡片后的跳转页面，仅限本小程序内的页面。支持带参数,（示例index?foo=bar）。该字段不填则模板无跳转。
		$data['page'] = "/pages/index/index" ;
	
		//模板内容，格式形如 { "key1": { "value": any }, "key2": { "value": any } }
		$data['data'] = [
			"time1" => [
				"value"=> $txt_info
			],
			"thing2" => [
				"value"=> $txt_name
			],
			"phone_number4" =>[
				"value"=> $mobile
			],
			"number5" => [
				"value"=> "1"
			],
			"thing6" => [
				"value"=> '请在预约的时间到达场馆！'
			]
		];
	
		//跳转小程序类型：developer为开发版；trial为体验版；formal为正式版；默认为正式版
		$data['miniprogram_state'] = 'developer' ;
	
		$ret = $this->curlPost($url,json_encode($data)) ;
        return $ret;
	}
	//发送post请求
	protected function curlPost($url,$data)
	{
		$ch = curl_init();
		$params[CURLOPT_URL] = $url;    //请求url地址
		$params[CURLOPT_HEADER] = FALSE; //是否返回响应头信息
		$params[CURLOPT_SSL_VERIFYPEER] = false;
		$params[CURLOPT_SSL_VERIFYHOST] = false;
		$params[CURLOPT_RETURNTRANSFER] = true; //是否将结果返回
		$params[CURLOPT_POST] = true;
		$params[CURLOPT_POSTFIELDS] = $data;
		curl_setopt_array($ch, $params); //传入curl参数
		$content = curl_exec($ch); //执行
		curl_close($ch); //关闭连接
		return $content;
	}

}